﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.API.Command.Role;
using RBAC.API.DTOs;

namespace RBAC.API.Handler.Role
{
    public class RoleGetHandler : IRequestHandler<RoleGetCommand, ApiPaging<RoleDTO>>
    {
        private readonly IRepository<RoleModel> roleway;
        private readonly IRepository<RolePermissionModel> rolepermissionway;
        private readonly IRepository<PermissionModel> permissionway;
        private readonly IMapper mapper;
        private readonly ILogger<RoleGetHandler> log;
        private readonly IHttpContextAccessor httpContextAccessor;

        public RoleGetHandler(IRepository<RoleModel> roleway, IRepository<RolePermissionModel> rolepermissionway, 
            IRepository<PermissionModel> permissionway, IMapper mapper, ILogger<RoleGetHandler> log,IHttpContextAccessor httpContextAccessor)
        {
            this.roleway = roleway;
            this.rolepermissionway = rolepermissionway;
            this.permissionway = permissionway;
            this.mapper = mapper;
            this.log = log;
            this.httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>角色列表</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiPaging<RoleDTO>> Handle(RoleGetCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<RoleDTO> res = new ApiPaging<RoleDTO>();
            try
            {
                var role = roleway.GetAll().Where(x => x.IsDel == false).AsNoTracking();
                if (!string.IsNullOrEmpty(request.RoleName))
                {
                    role = role.Where(x => x.RoleName.Contains(request.RoleName));
                }
                var linq = mapper.Map<List<RoleDTO>>(role);
                var rolepermission = rolepermissionway.GetAll().Where(x => x.IsDel == false).AsNoTracking();
                var permission = permissionway.GetAll().Where(x => x.IsDel == false).AsNoTracking();
           
                foreach (var item in linq)
                {
                    var link = from rp in rolepermission.Where(x=>x.RoleId==item.Id) join p in permission on rp.PermissionId equals p.Id select new { rp, p };
                    item.PermissionNames = string.Join(",",link.Select(x => x.p.PermissionName));//分割拼接
                    item.CheckedPermissions = string.Join(",", link.Select(x => x.rp.PermissionId)); //拼接选中的权限主键
                }
                

                log.LogInformation($"{DateTime.Now}时{httpContextAccessor.HttpContext?.User.Claims?.FirstOrDefault(x=>x.Type=="UserName")?.Value??"这是默认值"}");
                res.Totalcount = linq.Count();
                res.Message = $"获取角色列表成功";
                res.Code = StateCode.OK;
                res.PageData = linq.OrderBy(x => x.Id).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize).ToList();
                return Task.FromResult(res);

            }
            catch (Exception ex)
            {
                log.LogError($"获取角色列表时发生{ex.Message}");
                throw;
            }
        }
    }
}
